// pages/thingDetail/thingDetail.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    thingId: '',
    detailData: {
      isWished: false, // 新增字段，标记是否已经添加心愿
      isCollected: false, // 新增字段，标记是否已经收藏
      wishId: null,
      collectId: null
    },
    tabUnderLeft: 10,
    selectTabIndex: 0,
    commentData: [],
    recommendData: [],
    sortIndex: 0,
    order: 'recent',
    commentInput: '',
    // 修改为存储每个评论的点赞状态
    commentLikeStatus: {},
    BASE_URL: 'http://127.0.0.1:9100/api',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    wx.showLoading({
      title: '加载中...'
    });

    try {
      this.setData({
        thingId: options.id
      });
      await this.getThingDetail(); // 确保这里调用了 getThingDetail
      this.getRecommendThing();
      this.getCommentList();
      if (options.item) {
        try {
          const item = JSON.parse(decodeURIComponent(options.item));
          this.setData({
            detailItem: item
          });
        } catch (error) {
          console.error('解析传递的数据时出错:', error);
        }
      }
    } catch (error) {
      console.error('页面加载时出错:', error);
    } finally {
      wx.hideLoading();
    }
  },

  // 新增返回方法
  goBack() {
    wx.navigateBack({
      delta: 1 // 返回上一级页面
    });
  },

  selectTab(e) {
    const index = parseInt(e.currentTarget.dataset.index, 10);
    const query = wx.createSelectorQuery();
    query.selectAll('.tab').boundingClientRect();
    query.exec((res) => {
      const tabWidths = res[0].map(item => item.width);
      let leftOffset = 10;
      for (let i = 0; i < index; i++) {
        leftOffset += tabWidths[i];
      }
      this.setData({
        selectTabIndex: index,
        tabUnderLeft: leftOffset
      }, () => {
        // console.log('更新后的 selectTabIndex:', this.data.selectTabIndex);
      });
    });
  },

  async getThingDetail() {
    const app = getApp();
    const userId = app.globalData.userId;
    const token = app.globalData.token;
    const {
      thingId
    } = this.data;

    try {
      // 先获取景区详情
      const detailRes = await this.requestAsync(`http://localhost:9100/api/thing/detail?id=${thingId}`, 'GET');
      // console.log('景区详情请求结果:', detailRes.data); // 添加日志输出
      if (detailRes.data.code === 200) {
        let detailData = detailRes.data.data;
        const {
          BASE_URL
        } = this.data;
        detailData.cover = `${BASE_URL}/staticfiles/image/${detailData.cover}`;

        if (userId && token) {
          // 检查心愿状态
          const wishRes = await this.requestAsync(`http://localhost:9100/api/thingWish/getUserWishList?userId=${userId}`, 'GET', {
            'TOKEN': token,
            'Content-Type': 'application/x-www-form-urlencoded'
          });
          // console.log('心愿列表请求结果:', wishRes.data); // 添加日志输出
          if (wishRes.data.code === 200) {
            const wishList = wishRes.data.data;
            const isWished = wishList.some(item => item.thing_id === parseInt(thingId) && item.user_id === parseInt(userId));
            if (isWished) {
              detailData.isWished = true;
              const wishedItem = wishList.find(item => item.thing_id === parseInt(thingId) && item.user_id === parseInt(userId));
              detailData.wishId = wishedItem.id;
            } else {
              detailData.isWished = false;
              detailData.wishId = null;
            }
          } else {
            detailData.isWished = false;
            detailData.wishId = null;
          }

          // 检查收藏状态
          const collectRes = await this.requestAsync(`http://localhost:9100/api/thingCollect/getUserCollectList?userId=${userId}`, 'GET', {
            'TOKEN': token,
            'Content-Type': 'application/x-www-form-urlencoded'
          });
          // console.log('收藏列表请求结果:', collectRes.data); // 添加日志输出
          if (collectRes.data.code === 200) {
            const collectList = collectRes.data.data;
            const isCollected = collectList.some(item => item.thing_id === parseInt(thingId) && item.user_id === parseInt(userId));
            if (isCollected) {
              detailData.isCollected = true;
              const collectedItem = collectList.find(item => item.thing_id === parseInt(thingId) && item.user_id === parseInt(userId));
              detailData.collectId = collectedItem.id;
            } else {
              detailData.isCollected = false;
              detailData.collectId = null;
            }
          } else {
            detailData.isCollected = false;
            detailData.collectId = null;
          }
        } else {
          detailData.isWished = false;
          detailData.wishId = null;
          detailData.isCollected = false;
          detailData.collectId = null;
        }

        this.setData({
          detailData
        }, () => {
          console.log('更新后的 detailData:', {
            isWished: this.data.detailData.isWished,
            isCollected: this.data.detailData.isCollected,
            wishId: this.data.detailData.wishId,
            collectId: this.data.detailData.collectId
          });
        });
      } else {
        wx.showToast({
          title: '获取详情失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('获取景区详情时出错:', error);
      wx.showToast({
        title: '请求失败',
        icon: 'none'
      });
    }
  },

  // 封装 wx.request 为 Promise
  requestAsync(url, method, header = {}, data = {}) {
    return new Promise((resolve, reject) => {
      wx.request({
        url,
        method,
        header,
        data,
        success: resolve,
        fail: reject
      });
    });
  },

  // 定义 心愿addToWish 方法
  async addToWish() {
    const app = getApp();
    const userId = app.globalData.userId;
    const token = app.globalData.token;
    if (userId && token) {
      const {
        thingId,
        detailData
      } = this.data;
      const wishId = detailData.wishId;
      const url = detailData.isWished ? 'http://localhost:9100/api/thingWish/unWish' : 'http://localhost:9100/api/thingWish/wish';
      const method = 'POST';
      const data = detailData.isWished ? {
        id: wishId
      } : {
        thingId,
        userId
      };

      try {
        const res = await this.requestAsync(url, method, {
          'TOKEN': token,
          'Content-Type': 'application/x-www-form-urlencoded'
        }, data);
        console.log('心愿操作请求结果:', res.data); // 添加日志输出
        if (res.data.code === 200) {
          wx.showToast({
            title: res.data.msg,
            icon: 'success'
          });
          await this.getThingDetail(); // 重新获取详情以更新状态
        } else {
          wx.showToast({
            title: '操作失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('添加心愿请求出错:', error);
        wx.showToast({
          title: '请求失败',
          icon: 'none'
        });
      }
    } else {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
    }
  },

  // 定义 收藏collect 方法
  async collect() {
    const app = getApp();
    const userId = app.globalData.userId;
    const token = app.globalData.token;
    if (userId && token) {
      const {
        thingId,
        detailData
      } = this.data;
      const collectId = detailData.collectId;
      const url = detailData.isCollected ? 'http://localhost:9100/api/thingCollect/unCollect' : 'http://localhost:9100/api/thingCollect/collect';
      const method = 'POST';
      const data = detailData.isCollected ? {
        id: collectId
      } : {
        thingId,
        userId
      };

      try {
        const res = await this.requestAsync(url, method, {
          'TOKEN': token,
          'Content-Type': 'application/x-www-form-urlencoded'
        }, data);
        console.log('收藏操作请求结果:', res.data); // 添加日志输出
        if (res.data.code === 200) {
          wx.showToast({
            title: res.data.msg,
            icon: 'success'
          });
          await this.getThingDetail(); // 重新获取详情以更新状态
        } else {
          wx.showToast({
            title: '操作失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('收藏请求出错:', error);
        wx.showToast({
          title: '请求失败',
          icon: 'none'
        });
      }
    } else {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
    }
  },

  // 定义 getRecommendThing 方法
  getRecommendThing() {
    const BASE_URL = this.data.BASE_URL;
    wx.request({
      url: `${BASE_URL}/thing/list`,
      method: 'GET',
      success: (res) => {
        if (res.data.code === 200) {
          const recommendData = res.data.data;
          recommendData.forEach(item => {
            // console.log('处理前的 item:', item); // 添加日志输出
            item.cover = `${BASE_URL}/staticfiles/image/${item.cover}`;
            // console.log('处理后的 item:', item); // 添加日志输出
          });
          this.setData({
            recommendData
          });
        } else {
          wx.showToast({
            title: '获取推荐数据失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '请求失败',
          icon: 'none'
        });
      }
    });
  },

  // 定义时间转换函数
  formatTimestamp(timestamp) {
    const date = new Date(parseInt(timestamp));
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  },

  // 定义 getCommentList 方法
  getCommentList() {
    const thingId = this.data.thingId;
    const order = this.data.order;
    wx.request({
      url: `http://localhost:9100/api/comment/listThingComments?thingId=${thingId}&order=${order}`,
      method: 'GET',
      success: (res) => {
        if (res.data.code === 200) {
          const commentData = res.data.data;
          // 遍历评论数据，转换时间戳
          commentData.forEach(item => {
            if (item.commentTime) {
              item.commentTime = this.formatTimestamp(item.commentTime);
            }
          });
          this.setData({
            commentData
          });
        } else {
          wx.showToast({
            title: '获取评论数据失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '请求失败',
          icon: 'none'
        });
      }
    });
  },

  // 接收评论输入框内容
  onCommentInput: function (e) {
    const inputValue = e.detail.value;
    console.log('输入框当前输入的值:', inputValue);
    this.setData({
      commentInput: inputValue
    }, () => {
      console.log('更新后的 commentInput 值:', this.data.commentInput);
    });
  },

  // 定义 添加评论 sendComment 方法
  sendComment() {
    const app = getApp();
    const userId = app.globalData.userId;
    const token = app.globalData.token;
    if (userId && token) {
      const comment = this.data.commentInput;
      // 打印输入框获取的评论内容，确认输入框值获取是否正确
      console.log('从输入框获取的评论内容:', comment);
      console.log('发送的评论数据:', {
        thingId: this.data.thingId,
        userId: userId,
        content: comment
      });

      // 打印即将发送的请求参数，确认接口调用时参数是否正确
      const requestData = {
        thingId: this.data.thingId,
        userId: userId,
        content: comment
      };
      console.log('即将发送的请求参数:', requestData);

      wx.request({
        url: 'http://localhost:9100/api/comment/create',
        method: 'POST',
        header: {
          'TOKEN': token,
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        data: requestData,
        success: (res) => {
          if (res.data.code === 200) {
            wx.showToast({
              title: '评论成功',
              icon: 'success'
            });
            this.setData({
              commentInput: ''
            });
            this.getCommentList();
          } else {
            // 打印请求成功但业务逻辑失败时的响应数据，方便排查问题
            console.log('评论请求成功，但业务逻辑失败，响应数据:', res.data);
            wx.showToast({
              title: '评论失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          // 打印请求失败时的错误信息，方便排查问题
          console.log('评论请求失败，错误信息:', err);
          wx.showToast({
            title: '请求失败',
            icon: 'none'
          });
        }
      });
    } else {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
    }
  },

  // 定义点击热门景区模块跳转handleDetail方法定义
  handleDetail(e) {
    const thingId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/thingDetail/thingDetail?id=${thingId}`
    });
  },


  // 点赞方法
  // 点赞方法
  async like(e) {
    const app = getApp();
    const userId = app.globalData.userId;
    const token = app.globalData.token;
    if (userId && token) {
      const commentId = e.currentTarget.dataset.id;
      const {
        commentLikeStatus,
        commentData
      } = this.data;

      // 切换点赞状态
      const newLikeStatus = !commentLikeStatus[commentId];
      const newCommentLikeStatus = {
        ...commentLikeStatus,
        [commentId]: newLikeStatus
      };

      try {
        const res = await this.requestAsync('http://localhost:9100/api/comment/like', 'POST', {
          'TOKEN': token,
          'Content-Type': 'application/x-www-form-urlencoded'
        }, {
          id: commentId
        });

        if (res.data.code === 200) {
          wx.showToast({
            title: newLikeStatus ? '点赞成功' : '取消点赞成功',
            icon: 'success'
          });
          // 更新评论数据中的点赞数量
          const newCommentData = commentData.map(item => {
            if (item.id === commentId) {
              return {
                ...item,
                // 根据点赞状态更新点赞数量
                likeCount: parseInt(item.likeCount, 10) + (newLikeStatus ? 1 : -1)
              };
            }
            return item;
          });
          this.setData({
            commentLikeStatus: newCommentLikeStatus,
            commentData: newCommentData
          }, () => {
            console.log('更新后的 commentLikeStatus:', this.data.commentLikeStatus);
            console.log('更新后的 commentData:', this.data.commentData);
          });
        } else {
          wx.showToast({
            title: '操作失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('点赞请求出错:', error);
        wx.showToast({
          title: '请求失败',
          icon: 'none'
        });
      }
    } else {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
    }
  },

  // 处理立即预定点击事件
  handleOrder() {
    const app = getApp();
    const userId = app.globalData.userId;
    const token = app.globalData.token;

    if (userId && token) {
      const { thingId, detailData } = this.data;
      const { title, cover, price } = detailData;
      wx.navigateTo({
        url: `/pages/orderDetail/orderDetail?id=${thingId}&title=${encodeURIComponent(title)}&cover=${encodeURIComponent(cover)}&price=${price}`
      });
    } else {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
});